package com.jl.server;

import com.alibaba.fastjson.JSON;
import com.jl.bean.CityBean;
import com.jl.tool.JDBCconnection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;

public class CityServer extends HttpServlet{
    private Connection connection;
    private PreparedStatement preparedStatement;
    private ResultSet resultSet;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JDBCconnection jdbCconnection = new JDBCconnection();
        String sid = req.getParameter("sid");
        resp.setContentType("application/json;charset=utf-8");

        try{
            connection = jdbCconnection.connection();
            preparedStatement = connection.prepareStatement("select * from city where sid=?");
            preparedStatement.setInt(1,Integer.parseInt(sid));
            resultSet = preparedStatement.executeQuery();
            ArrayList<CityBean> cityBeans = new ArrayList<>();
            while (resultSet.next()){
                CityBean cityBean = new CityBean();
                cityBean.setId(resultSet.getInt("id"));
                cityBean.setName(resultSet.getString("name"));
                cityBeans.add(cityBean);
            }
            String s = JSON.toJSONString(cityBeans);
            resp.getWriter().write(s);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                resultSet.close();
                preparedStatement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }
}
